import axios from 'axios'
import { message,Modal } from "antd";
import store from '../store'; // 修复导入路径
import { logout } from '@/store/user';

const service = axios.create({
  timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 直接从store中获取token
    const state = store.getState();
    const token = state.user.token;
    
    if (token) {
      config.headers.Authorization = token;
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code != "200") {
      if (res.code === "2006" || res.code === "2001") {
          Modal.info({
              title: '提示',
              content: res.msg,
              onOk: () => {
                // 清除store中的用户信息
                store.dispatch(logout());
                window.location.href = '/login';
              }
          });
      } else {
        message.error(res.msg)
      }
      return Promise.reject(new Error(res.msg))
    } else {
      return res
    }
  },
  error => {
    console.log(error)
    message.error('服务器异常，请稍后再试！')
    return Promise.reject(error)
  }
)

service.post = (url, data,loading) => {
  return service({
    method: 'post',
    url,
    data: data,
    loading: loading
  })
}

service.get = (url, params,loading) => {
  return service({
    method: 'get',
    url,
    params,
    loading: loading
  })
}

service.delete = (url, params,loading) => {
  return service({
    method: 'delete',
    url,
    params,
    loading: loading
  })
}

export default service